package com.schtkc.fishingmaster.config;


import com.schtkc.fishingmaster.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;


/**
 * GlobalWebMvcConfig
 *
 * @Author: ydz
 * @CreateTime: 2022-06-06  17:03
 */
@Configuration
@EnableWebMvc
public class AdminWebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

                String authHeader = request.getHeader(Constants.TOKEN_KEY);
                System.out.println("Authorization=" + authHeader);
                String tKey = "Bearer ";

                if (authHeader != null && authHeader.length() > 0 && authHeader.contains(tKey)) {
                    int index = authHeader.indexOf(tKey);
                    String token = authHeader.substring(index + tKey.length());
                    System.out.println("当前请求头中的 token");
                    System.out.println(token);

                    String tokenRedis = redisTemplate.opsForValue().get(token);
                    System.out.println("tokenRedis");
                    System.out.println(tokenRedis);
                    if (tokenRedis != null) {
                        System.out.println("redis token校验通过");
                        return true;
                    }

                }
                System.out.println("没有token");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
        }).addPathPatterns("/**")
//        https://api.weixin.qq.com/
                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**")
                .excludePathPatterns("/**/configs/**", "/**/verifyCode/**",
                        "/**/user/registerByPhonePwd", "/**/user/registerByPhonePwdVCode",
                        "/**/user/loginByWx", "/**/user/loginByPhonePwd", "/**/user/loginByPhoneVCode",
                        "/**/admin/v1/login", "/**/admin/v1/register", "/**/dlogs/**", "/**/systemTime");
    }

//    /**
//     * 重写父类提供的跨域请求处理的接口
//     *
//     * @param registry
//     */
//    @Override
//    public void addCorsMappings(CorsRegistry registry) {
//        //设置允许跨域的路劲
//        registry.addMapping("/**")
//                //设置允许跨域请求的域名
////                .allowedOrigins("*")
//                .allowedOriginPatterns("*")
//                //设置允许的方法
////                .allowedMethods("GET", "POST", "DELETE", "OPTIONS")
//                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
//                //允许的请求头
//                .allowedHeaders("*")
//                //跨域允许时间
//                .maxAge(3600)
//                //是否允许证书 不在默认开启
//                .allowCredentials(true)
//                // 暴露哪些头部信息（因为跨域访问默认不能获取全部头部信息）
//                .exposedHeaders("Server", "Content-Length", Constants.TOKEN_KEY,
//                        "Access-Token",
//                        "Access-Control-Allow-Origin",
//                        "Access-Control-Allow-Credentials");
//    }

    private CorsConfiguration corsConfig() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOriginPattern("*");
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        configuration.setAllowCredentials(true);
        configuration.setMaxAge(3600L);
        List<String> expsHeaders = new ArrayList<>();
        expsHeaders.add("Server");
        expsHeaders.add("Content-Length");
        expsHeaders.add(Constants.TOKEN_KEY);
        expsHeaders.add("Access-Token");
        expsHeaders.add("Access-Control-Allow-Origin");
        expsHeaders.add("Access-Control-Allow-Credentials");
        configuration.setExposedHeaders(expsHeaders);
        return configuration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig());
        return new CorsFilter(source);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}
